import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;



/**
 * @author：刘东
 * @created: 2013-4-22 下午02:23:59 
 * @version：$Id$ 
 * @since:1.0
 * @copyright 
 *
 */

public class JsonTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		/*		System.out.println("java代码封装为json字符串");
					JSONObject jsonObj = new JSONObject();

					try {
						jsonObj.put("username", "张三");
						jsonObj.put("password", "123456");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("java--->json \n" + jsonObj.toString());*/
		//数组转化
		List list = new ArrayList();
		list.add(0, "name");
		list.add(1, "name2");
		list.add(2, "name3");
		list.add(3, "name4");
		list.add(4, "name5");
		JSONArray jo = JSONArray.fromObject(list);
		String str = jo.getString(0);
		System.out.println(str);
		//字符串转化
		String jsonStr = "{\"password\":\"123456\",\"username\":\"张三\"}";
		JSONObject ob = JSONObject.fromObject(jsonStr);
		System.out.println(ob);
		//XML转化
		System.out.println("json字符串转xml字符串");
		String jsonStrXML = "{\"password\":\"123456\",\"username\":\"张三\"}";
		JSONObject json = JSONObject.fromObject(jsonStrXML);
		XMLSerializer xmlSerializer = new XMLSerializer();
		xmlSerializer.setRootName("user_info");
		xmlSerializer.setTypeHintsEnabled(false);
		String xml = xmlSerializer.write(json);
		System.out.println("json--->xml \n" + xml);
		//bean的转化
		System.out.println("javabean转json字符串");
		 UserInfo userInfo = new UserInfo();
		 userInfo.setName("张三");
		 userInfo.setPassword("123456");
		 JSONObject json1 = JSONObject.fromObject(userInfo);
		 System.out.println("javabean--->json \n" + json.toString());
		 System.out.println(json1.getString("name"));
	}

}
